// 通用工具函数

// 平台检测
export const platform = {
  // 是否为微信小程序
  isWeixin: () => {
    // #ifdef MP-WEIXIN
    return true
    // #endif
    return false
  },

  // 是否为H5
  isH5: () => {
    // #ifdef H5
    return true
    // #endif
    return false
  },

  // 是否为APP
  isApp: () => {
    // #ifdef APP-PLUS
    return true
    // #endif
    return false
  },

  // 是否为安卓
  isAndroid: () => {
    // #ifdef APP-PLUS
    return uni.getSystemInfoSync().platform === 'android'
    // #endif
    return false
  },

  // 是否为iOS
  isIOS: () => {
    // #ifdef APP-PLUS
    return uni.getSystemInfoSync().platform === 'ios'
    // #endif
    return false
  }
}

// 文件处理工具
export const fileUtils = {
  // 获取文件扩展名
  getExtension: (filename) => {
    if (!filename) return ''
    return filename.substring(filename.lastIndexOf('.')).toLowerCase()
  },

  // 获取文件大小显示
  formatFileSize: (bytes) => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  },

  // 检查文件类型是否支持
  isSupportedFile: (filename) => {
    const supportedExtensions = ['.txt', '.pdf', '.doc', '.docx', '.md', '.ppt', '.pptx', '.xls', '.xlsx', '.png', '.jpg', '.jpeg']
    const ext = fileUtils.getExtension(filename)
    return supportedExtensions.includes(ext)
  },

  // 选择文件（兼容多平台）
  chooseFile: (options = {}) => {
    return new Promise((resolve, reject) => {
      const defaultOptions = {
        count: 1,
        type: 'all',
        extension: []
      }
      
      const finalOptions = { ...defaultOptions, ...options }
      
      // 微信小程序
      if (platform.isWeixin()) {
        uni.chooseMessageFile({
          count: finalOptions.count,
          type: finalOptions.type,
          success: (res) => {
            resolve(res.tempFiles)
          },
          fail: reject
        })
      } else {
        // H5和APP
        uni.chooseFile({
          count: finalOptions.count,
          type: finalOptions.type,
          extension: finalOptions.extension,
          success: (res) => {
            resolve(res.tempFiles)
          },
          fail: reject
        })
      }
    })
  },

  // 选择图片
  chooseImage: (options = {}) => {
    return new Promise((resolve, reject) => {
      const defaultOptions = {
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera']
      }
      
      const finalOptions = { ...defaultOptions, ...options }
      
      uni.chooseImage({
        ...finalOptions,
        success: (res) => {
          resolve(res.tempFilePaths)
        },
        fail: reject
      })
    })
  }
}

// 日期时间工具
export const dateUtils = {
  // 格式化日期
  formatDate: (date, format = 'YYYY-MM-DD HH:mm:ss') => {
    if (!date) return ''
    
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hours = String(d.getHours()).padStart(2, '0')
    const minutes = String(d.getMinutes()).padStart(2, '0')
    const seconds = String(d.getSeconds()).padStart(2, '0')
    
    return format
      .replace('YYYY', year)
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hours)
      .replace('mm', minutes)
      .replace('ss', seconds)
  },

  // 相对时间
  fromNow: (date) => {
    if (!date) return ''
    
    const now = new Date()
    const target = new Date(date)
    const diff = now - target
    
    const minute = 60 * 1000
    const hour = 60 * minute
    const day = 24 * hour
    const month = 30 * day
    const year = 365 * day
    
    if (diff < minute) {
      return '刚刚'
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前'
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前'
    } else if (diff < month) {
      return Math.floor(diff / day) + '天前'
    } else if (diff < year) {
      return Math.floor(diff / month) + '个月前'
    } else {
      return Math.floor(diff / year) + '年前'
    }
  }
}

// 存储工具
export const storageUtils = {
  // 设置数据
  set(key, value) {
    try {
      uni.setStorageSync(key, value)
      return true
    } catch (error) {
      console.error('存储数据失败:', error)
      return false
    }
  },

  // 获取数据
  get(key, defaultValue = null) {
    try {
      const value = uni.getStorageSync(key)
      return value !== '' ? value : defaultValue
    } catch (error) {
      console.error('获取数据失败:', error)
      return defaultValue
    }
  },

  // 删除数据
  remove(key) {
    try {
      uni.removeStorageSync(key)
      return true
    } catch (error) {
      console.error('删除数据失败:', error)
      return false
    }
  },

  // 清空所有数据
  clear() {
    try {
      uni.clearStorageSync()
      return true
    } catch (error) {
      console.error('清空数据失败:', error)
      return false
    }
  },

  // 检查键是否存在
  has(key) {
    try {
      const value = uni.getStorageSync(key)
      return value !== '' && value !== null && value !== undefined
    } catch (error) {
      return false
    }
  }
}

// 网络请求工具
export const request = {
  // 基础配置
  baseURL: 'http://admin-yzy-two.wudkmao.top/api/v1',
  
  // 请求方法
  async request(options) {
    const { url, method = 'GET', data = {}, header = {} } = options
    
    return new Promise((resolve, reject) => {
      uni.request({
        url: this.baseURL + url,
        method,
        data,
        header: {
          'Content-Type': 'application/json',
          ...header
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`))
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },

  // GET 请求
  get(url, params = {}) {
    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
    const fullUrl = queryString ? `${url}?${queryString}` : url
    
    return this.request({
      url: fullUrl,
      method: 'GET'
    })
  },

  // POST 请求
  post(url, data = {}) {
    return this.request({
      url,
      method: 'POST',
      data
    })
  },

  // PUT 请求
  put(url, data = {}) {
    return this.request({
      url,
      method: 'PUT',
      data
    })
  },

  // DELETE 请求
  delete(url) {
    return this.request({
      url,
      method: 'DELETE'
    })
  }
}

// 工具函数
export const utils = {
  // 格式化时间
  formatTime(date) {
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hour = String(d.getHours()).padStart(2, '0')
    const minute = String(d.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 文件大小格式化
  formatFileSize(bytes) {
    if (bytes === 0) return '0 B'
    
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  },

  // 防抖函数
  debounce(func, wait) {
    let timeout
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout)
        func(...args)
      }
      clearTimeout(timeout)
      timeout = setTimeout(later, wait)
    }
  },

  // 节流函数
  throttle(func, limit) {
    let inThrottle
    return function() {
      const args = arguments
      const context = this
      if (!inThrottle) {
        func.apply(context, args)
        inThrottle = true
        setTimeout(() => inThrottle = false, limit)
      }
    }
  }
}

// 验证工具
export const validateUtils = {
  // 验证邮箱
  isEmail: (email) => {
    const reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return reg.test(email)
  },

  // 验证手机号
  isPhone: (phone) => {
    const reg = /^1[3-9]\d{9}$/
    return reg.test(phone)
  },

  // 验证密码强度
  checkPasswordStrength: (password) => {
    let strength = 0
    
    if (password.length >= 8) strength++
    if (/[a-z]/.test(password)) strength++
    if (/[A-Z]/.test(password)) strength++
    if (/[0-9]/.test(password)) strength++
    if (/[^a-zA-Z0-9]/.test(password)) strength++
    
    if (strength <= 2) return 'weak'
    if (strength <= 3) return 'medium'
    return 'strong'
  }
}

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

// 生成UUID
export const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

// 默认导出
export default {
  platform,
  fileUtils,
  dateUtils,
  storageUtils,
  request,
  utils,
  validateUtils,
  deepClone,
  generateUUID
}